package com.hll.erp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hll.erp.entity.Category;
import com.hll.erp.entity.ResultMap;
import com.hll.erp.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * (Category)表控制层
 *
 * @author makejava
 * @since 2021-07-04 15:17:54
 */
@RestController
@RequestMapping("category")
@Api(
    value = "Category Controller",
    tags = {"产品类别操作接口"})
public class CategoryController {
  /** 服务对象 */
  @Resource private CategoryService categoryService;

  @RequiresAuthentication
  @ApiOperation(value = "获取类别,根据id")
  @PostMapping("getCategory")
  public ResultMap getCategory(@RequestParam Integer id) {
    ResultMap resultMap = new ResultMap();
    Category category = categoryService.getById(id);
    if (category != null) {
      resultMap.success().code(200).message(category);
    } else {
      resultMap.fail().code(207).message("查无此类别");
    }
    return resultMap;
  }

  @RequiresAuthentication
  @ApiOperation(value = "获取类别列表")
  @PostMapping("/getCategories")
  public ResultMap getCategories() {
    List<Category> list = categoryService.list();
    return new ResultMap().success().code(200).message(list);
  }

  @RequiresRoles("admin")
  @ApiOperation(value = "添加类别")
  @PostMapping("/addCategory")
  public ResultMap addCategory(@RequestParam String name) {
    Category category =
        categoryService.getOne(new QueryWrapper<Category>().eq("name", name.replace(" ", "")));
    ResultMap resultMap = new ResultMap();
    if (category == null) {
      category = new Category();
      category.setName(name);
      if (categoryService.save(category)) {
        resultMap.success().code(200).message("添加成功");
      } else {
        resultMap.fail().code(201).message("数据库插入失败");
      }
    } else {
      resultMap.fail().code(203).message("分类已存在");
    }
    return resultMap;
  }
}
